// cloudfunctions/getConversations/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { userId } = event
    if (!userId) return { success: false, message: '参数缺失: userId 是必需参数' }
    
    // 1. 获取用户的所有会话状态
    const userConversationsRes = await db.collection('user_message_status')
      .where({ userId })
      .get()
      
    const userConversations = userConversationsRes.data || []
    if (userConversations.length === 0) {
      return { success: true, conversations: [] }
    }
    
    // 2. 提取会话ID并解析出商品ID（用于后续商品信息查询）
    const conversationIds = userConversations.map(item => item.conversationId);
    const goodsIds = [...new Set(conversationIds.map(id => id.split('_')[2]))]; // 从会话ID中提取goodsId
    
    // 3. 查询会话详情（包含buyerId和sellerId）
    const conversationRes = await db.collection('conversations')
      .where({
        conversationId: db.command.in(conversationIds)
      })
      .get()
    
    // 4. 获取最新消息详情
    const messageIds = conversationRes.data.map(convo => convo.latestMessage);
    const messageRes = await db.collection('messages')
      .where({
        _id: db.command.in(messageIds)
      })
      .get()
    
    // 5. 构建消息映射表
    const messageMap = messageRes.data.reduce((map, msg) => {
      map[msg._id] = msg
      return map
    }, {})
    
    // 6. 构建用户会话状态映射表
    const userStatusMap = userConversations.reduce((map, status) => {
      map[status.conversationId] = status
      return map
    }, {})
    
    // 7. 提取所有对方用户ID（买家或卖家）
    const otherUserIds = conversationRes.data.map(convo => 
      convo.buyerId === userId ? convo.sellerId : convo.buyerId
    )
    
    // 8. 查询对方用户信息
    const userRes = await db.collection('users')
      .where({
        _id: db.command.in(otherUserIds)
      })
      .get()
    
    // 9. 构建用户信息映射表
    const userInfoMap = userRes.data.reduce((map, user) => {
      map[user._id] = user
      return map
    }, {})
    
    // 10. 查询商品信息（如果有）
    const goodsRes = goodsIds.length > 0 ? 
      await db.collection('blindbox_goods')
        .where({
          _id: db.command.in(goodsIds)
        })
        .get() : { data: [] };
    
    // 11. 构建商品信息映射表
    const goodsInfoMap = goodsRes.data.reduce((map, goods) => {
      map[goods._id] = goods
      return map
    }, {})
    
    // 12. 组装会话数据（包含对方用户信息和商品信息）
    const result = conversationRes.data.map(convo => {
      const latestMessage = messageMap[convo.latestMessage] || {};
      const userStatus = userStatusMap[convo.conversationId] || {};
      
      // 确定对方用户ID和角色
      const otherUserId = convo.buyerId === userId ? convo.sellerId : convo.buyerId;
      const otherUserInfo = userInfoMap[otherUserId] || { _id: otherUserId, nickname: '未知用户' };
      
      // 从会话ID中提取goodsId
      const [, , goodsId] = convo.conversationId.split('_');
      const goodsInfo = goodsInfoMap[goodsId] || { _id: goodsId, name: '未知商品' };
      
      return {
        ...convo,
        latestMessage: latestMessage,
        unreadCount: userStatus.unreadCount || 0,
        updateTime: userStatus.updateTime || convo.updateTime,
        isDeleted: convo.isDeleted[userId] || false,
        otherUserInfo: otherUserInfo, // 对方用户信息
        goodsInfo: goodsInfo,       // 商品信息
        conversationId: convo.conversationId,
        buyerId: convo.buyerId,
        sellerId: convo.sellerId,
        goodsId: goodsId
      }
    }).filter(convo => !convo.isDeleted); // 过滤已删除的会话
    
    // 13. 按时间排序
    result.sort((a, b) => new Date(b.updateTime) - new Date(a.updateTime));
    
    return { 
      success: true, 
      conversations: result
    }
    
  } catch (error) {
    console.error('获取会话列表失败:', error)
    return { 
      success: false, 
      message: error.message || '获取会话列表失败' 
    }
  }
}